<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useTodoStore } from "../stores/todo";
import { useSettingsStore } from "../stores/settings";
import AutoResizeTextarea from "../components/AutoResizeTextarea.vue";
import ViewToolbar from "../components/ViewToolbar.vue";
import ConfirmDialog from "../components/ConfirmDialog.vue";
import { useTodoDelete } from "../composables/useTodoDelete";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { useAutoAnimate } from "@formkit/auto-animate/vue";

dayjs.locale("zh-cn");

const todoStore = useTodoStore();
const settingsStore = useSettingsStore();
const [todoListRef] = useAutoAnimate({ duration: 500 });
const { showDeleteConfirm, deleteTodo, confirmDelete, cancelDelete } =
  useTodoDelete();

const currentDate = ref(dayjs());
const selectedDate = ref<string>(dayjs().format("YYYY-MM-DD"));
const editingTodoId = ref<string | null>(null);
const editingContent = ref("");
const newTodoContent = ref("");
const hoveredId = ref<string | null>(null); // 鼠标悬停的待办 ID

// 获取周几的中文简写
function getWeekdayName(date: dayjs.Dayjs) {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return weekdays[date.day()];
}

// 当前月份的所有日期
const daysInMonth = computed(() => {
  const start = currentDate.value.startOf("month");
  const end = currentDate.value.endOf("month");
  const days: Array<{ date: dayjs.Dayjs; isCurrentMonth: boolean }> = [];

  // 填充上月日期
  const firstDayOfWeek = start.day();
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    days.push({
      date: start.subtract(i + 1, "day"),
      isCurrentMonth: false,
    });
  }

  // 填充当月日期
  for (let i = 0; i <= end.date() - 1; i++) {
    days.push({
      date: start.add(i, "day"),
      isCurrentMonth: true,
    });
  }

  // 填充下月日期
  const remaining = 42 - days.length;
  for (let i = 1; i <= remaining; i++) {
    days.push({
      date: end.add(i, "day"),
      isCurrentMonth: false,
    });
  }

  return days;
});

onMounted(async () => {
  await todoStore.loadTodos();
  await settingsStore.loadSettings();
});

// 获取指定日期的待办
function getTodosForDate(date: dayjs.Dayjs) {
  return todoStore.getTodosByDate(date.format("YYYY-MM-DD"));
}

// 上一月
function prevMonth() {
  currentDate.value = currentDate.value.subtract(1, "month");
}

// 下一月
function nextMonth() {
  currentDate.value = currentDate.value.add(1, "month");
}

// 选择日期
function selectDate(date: string) {
  selectedDate.value = date;
  newTodoContent.value = "";
  editingTodoId.value = null;
  editingContent.value = "";
}

// 添加待办
function addTodoForDate() {
  if (newTodoContent.value.trim() && selectedDate.value) {
    todoStore.addTodo(newTodoContent.value.trim(), selectedDate.value);
    newTodoContent.value = "";
  }
}

// 开始编辑
function startEdit(id: string, content: string) {
  editingTodoId.value = id;
  editingContent.value = content;
}

// 保存编辑
function saveEdit() {
  if (editingTodoId.value && editingContent.value.trim()) {
    todoStore.updateTodo(editingTodoId.value, {
      content: editingContent.value.trim(),
    });
  }
  editingTodoId.value = null;
  editingContent.value = "";
}

// 取消编辑
function cancelEdit() {
  editingTodoId.value = null;
  editingContent.value = "";
}

// 切换完成状态
function toggleComplete(id: string) {
  todoStore.toggleComplete(id);
}

// 回到今天
function goToToday() {
  currentDate.value = dayjs();
  selectedDate.value = dayjs().format("YYYY-MM-DD");
}

// 设置优先级
function setPriority(id: string, priority?: "high" | "medium" | "low") {
  todoStore.setPriority(id, priority);
}

// 循环切换优先级
function cyclePriority(id: string) {
  todoStore.cyclePriority(id);
}

// 获取优先级颜色类名
function getPriorityClass(priority?: string) {
  if (!priority) return "";
  return `priority-${priority}`;
}

// 获取选中日期的排序后的待办
const selectedDateTodos = computed(() => {
  const todos = todoStore.getTodosByDate(selectedDate.value);
  return todoStore.getSortedTodos(todos);
});
</script>

<template>
  <div class="calendar-view">
    <!-- 顶部工具栏 -->
    <ViewToolbar
      title="待办日历"
      view-mode="calendar"
      @go-to-today="goToToday"
    />

    <!-- 主内容区域 - 左右布局 -->
    <div class="main-content">
      <!-- 左侧日历区域 -->
      <div class="calendar-section">
        <!-- 月份选择器 -->
        <div class="month-selector">
          <button @click="prevMonth" class="nav-btn">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <polyline points="15 18 9 12 15 6"></polyline>
            </svg>
          </button>
          <span class="month-label">{{
            currentDate.format("YYYY年MM月")
          }}</span>
          <button @click="nextMonth" class="nav-btn">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <polyline points="9 18 15 12 9 6"></polyline>
            </svg>
          </button>
        </div>

        <!-- 星期标题 -->
        <div class="weekdays">
          <div class="weekday">日</div>
          <div class="weekday">一</div>
          <div class="weekday">二</div>
          <div class="weekday">三</div>
          <div class="weekday">四</div>
          <div class="weekday">五</div>
          <div class="weekday">六</div>
        </div>

        <!-- 日历网格 -->
        <div class="calendar-grid">
          <div
            v-for="day in daysInMonth"
            :key="day.date.format('YYYY-MM-DD')"
            class="day-cell"
            :class="{
              'other-month': !day.isCurrentMonth,
              today:
                day.date.format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD'),
              selected: selectedDate === day.date.format('YYYY-MM-DD'),
            }"
            @click="selectDate(day.date.format('YYYY-MM-DD'))"
          >
            <div class="day-number">{{ day.date.date() }}</div>
            <div class="todos-preview">
              <div
                v-for="todo in getTodosForDate(day.date).slice(0, 2)"
                :key="todo.id"
                class="todo-preview-item"
                :class="{ completed: todo.completed }"
              >
                <div
                  v-if="todo.priority"
                  class="mini-priority-bar"
                  :class="getPriorityClass(todo.priority)"
                ></div>
                <span class="todo-preview-text">{{ todo.content }}</span>
              </div>
              <div
                v-if="getTodosForDate(day.date).length > 2"
                class="more-indicator"
              >
                +{{ getTodosForDate(day.date).length - 2 }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧待办详情区域 -->
      <div class="selected-date-detail">
        <div class="detail-header">
          <h2>
            {{ dayjs(selectedDate).format("M月D日") }}
            {{ getWeekdayName(dayjs(selectedDate)) }}
          </h2>
          <span class="todo-count">
            {{ getTodosForDate(dayjs(selectedDate)).length }} 个待办
          </span>
        </div>

        <div class="detail-content">
          <!-- 待办列表 -->
          <div
            v-if="selectedDateTodos.length > 0"
            class="todo-list"
            ref="todoListRef"
          >
            <div
              v-for="todo in selectedDateTodos"
              :key="todo.id"
              class="todo-item"
              @mouseenter="hoveredId = todo.id"
              @mouseleave="hoveredId = null"
            >
              <!-- 优先级色条 -->
              <div
                class="priority-bar"
                :class="getPriorityClass(todo.priority)"
                @click.stop="cyclePriority(todo.id)"
                title="点击切换优先级"
              ></div>

              <input
                type="checkbox"
                :checked="todo.completed"
                @change="toggleComplete(todo.id)"
                class="checkbox"
              />
              <div
                v-if="editingTodoId !== todo.id"
                @click="startEdit(todo.id, todo.content)"
                class="todo-text"
                :class="{ completed: todo.completed }"
              >
                {{ todo.content }}
              </div>
              <AutoResizeTextarea
                v-else
                v-model="editingContent"
                class="todo-input"
                :autofocus="true"
                @enter="saveEdit"
                @blur="saveEdit"
                @esc="cancelEdit"
              />

              <!-- 优先级选择器 -->
              <div
                class="priority-selector"
                v-show="hoveredId === todo.id && editingTodoId !== todo.id"
              >
                <button
                  @click.stop="setPriority(todo.id, 'high')"
                  class="priority-btn high"
                  :class="{ active: todo.priority === 'high' }"
                  title="高优先级"
                >
                  <span class="priority-dot"></span>
                </button>
                <button
                  @click.stop="setPriority(todo.id, 'medium')"
                  class="priority-btn medium"
                  :class="{ active: todo.priority === 'medium' }"
                  title="中优先级"
                >
                  <span class="priority-dot"></span>
                </button>
                <button
                  @click.stop="setPriority(todo.id, 'low')"
                  class="priority-btn low"
                  :class="{ active: todo.priority === 'low' }"
                  title="低优先级"
                >
                  <span class="priority-dot"></span>
                </button>
                <button
                  @click.stop="setPriority(todo.id, undefined)"
                  class="priority-btn none"
                  :class="{ active: !todo.priority }"
                  title="无优先级"
                >
                  <span class="priority-dot"></span>
                </button>
              </div>

              <button
                @click.stop="deleteTodo(todo.id)"
                class="delete-btn"
                title="删除"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-else class="empty-state">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="48"
              height="48"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path d="M9 11l3 3L22 4"></path>
              <path
                d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"
              ></path>
            </svg>
            <p>暂无待办事项</p>
          </div>

          <!-- 添加新待办 -->
          <div class="add-todo">
            <AutoResizeTextarea
              v-model="newTodoContent"
              placeholder="添加待办事项..."
              class="new-todo-input"
              @enter="addTodoForDate"
            />
            <button @click="addTodoForDate" class="add-btn">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 删除确认对话框 -->
  <ConfirmDialog
    v-model:show="showDeleteConfirm"
    title="删除待办"
    message="确定要删除这条待办事项吗？此操作无法撤销。"
    confirm-text="删除"
    cancel-text="取消"
    @confirm="confirmDelete"
    @cancel="cancelDelete"
  />
</template>

<style scoped>
.calendar-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: var(--bg-primary);
  overflow: hidden;
}

/* 主内容区域 - 左右布局 */
.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
  min-height: 0;
  padding: 20px;
}

/* 左侧日历区域 */
.calendar-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0;
}

.month-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.nav-btn {
  background: none;
  border: none;
  color: var(--text-primary);
  cursor: pointer;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: background 0.2s;
}

.nav-btn:hover {
  background: var(--bg-secondary);
}

.month-label {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  min-width: 140px;
  text-align: center;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 6px;
  margin-bottom: 6px;
  flex-shrink: 0;
}

.weekday {
  text-align: center;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-secondary);
  padding: 6px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 6px;
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
  align-content: start;
}

.calendar-grid::-webkit-scrollbar {
  width: 6px;
}

.calendar-grid::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 3px;
}

.calendar-grid::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}

.day-cell {
  background: var(--bg-secondary);
  border: 2px solid var(--border-color);
  border-radius: 8px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  aspect-ratio: 1;
  overflow: hidden;
}

.day-cell:hover {
  border-color: var(--text-secondary);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.day-cell.other-month {
  opacity: 0.3;
}

.day-cell.today {
  border-color: var(--border-color);
  background: rgba(34, 197, 94, 0.05);
  border-color: #ffffff;
}

.day-cell.today.selected {
  border-color: #22c55e;
}

.day-cell.selected {
  border-color: #22c55e;
  background: rgba(34, 197, 94, 0.15);
  box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}

.day-number {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
  flex-shrink: 0;
}

.todos-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  overflow: hidden;
}

.todo-preview-item {
  font-size: 10px;
  color: var(--text-primary);
  background: var(--bg-primary);
  padding: 3px 5px;
  border-radius: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 4px;
  position: relative;
}

.todo-preview-item .mini-priority-bar {
  width: 2px;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  border-radius: 3px 0 0 3px;
}

.todo-preview-item .mini-priority-bar.priority-high {
  background: #ef4444;
}

.todo-preview-item .mini-priority-bar.priority-medium {
  background: #f59e0b;
}

.todo-preview-item .mini-priority-bar.priority-low {
  background: #3b82f6;
}

.todo-preview-item .todo-preview-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

.todo-preview-item.completed {
  text-decoration: line-through;
  color: var(--text-secondary);
  opacity: 0.6;
}

.more-indicator {
  font-size: 9px;
  color: var(--text-secondary);
  padding: 2px 5px;
  text-align: center;
  font-weight: 600;
}

/* 右侧待办详情区域 */
.selected-date-detail {
  width: 360px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  flex-shrink: 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

.detail-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.todo-count {
  font-size: 13px;
  color: var(--text-secondary);
  background: var(--bg-primary);
  padding: 4px 10px;
  border-radius: 12px;
  white-space: nowrap;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.todo-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow-y: auto;
  flex: 1;
  padding-right: 4px;
}

.todo-list::-webkit-scrollbar {
  width: 6px;
}

.todo-list::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 3px;
}

.todo-list::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background: var(--bg-primary);
  border-radius: 8px;
  border: 1px solid var(--border-color);
  position: relative;
}

.todo-item:hover {
  border-color: var(--text-secondary);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 优先级色条 */
.todo-item .priority-bar {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  border-radius: 8px 0 0 8px;
  cursor: pointer;
  transition: width 0.2s ease;
  z-index: 1;
}

.todo-item:hover .priority-bar {
  width: 5px;
}

.todo-item .priority-bar.priority-high {
  background: #ef4444;
}

.todo-item .priority-bar.priority-medium {
  background: #f59e0b;
}

.todo-item .priority-bar.priority-low {
  background: #3b82f6;
}

/* 优先级选择器 */
.todo-item .priority-selector {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
  margin-right: 4px;
}

.todo-item:hover .priority-selector {
  opacity: 1;
}

.todo-item .priority-btn {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid var(--border-color);
  background: var(--bg-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.todo-item .priority-btn:hover {
  transform: scale(1.15);
  border-color: var(--text-primary);
}

.todo-item .priority-btn.active {
  border-width: 2.5px;
  transform: scale(1.1);
}

.todo-item .priority-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: block;
}

.todo-item .priority-btn.high .priority-dot {
  background: #ef4444;
}

.todo-item .priority-btn.medium .priority-dot {
  background: #f59e0b;
}

.todo-item .priority-btn.low .priority-dot {
  background: #3b82f6;
}

.todo-item .priority-btn.none .priority-dot {
  background: var(--border-color);
}

.todo-item .priority-btn.active .priority-dot {
  box-shadow: 0 0 0 2px var(--bg-primary);
}

.checkbox {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: #22c55e;
}

.todo-text {
  flex: 1;
  font-size: 14px;
  color: var(--text-primary);
  cursor: pointer;
  word-break: break-word;
  line-height: 1.5;
  padding: 4px;
  border-radius: 4px;
  transition: background 0.2s;
}

.todo-text:hover {
  background: var(--bg-secondary);
}

.todo-text.completed {
  text-decoration: line-through;
  color: var(--text-secondary);
  opacity: 0.6;
}

.todo-input {
  flex: 1;
  font-size: 14px;
  padding: 8px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  outline: none;
}

.delete-btn {
  flex-shrink: 0;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  opacity: 0;
  transition: all 0.2s;
}

.todo-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background: #ef4444;
  color: white;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--text-secondary);
  flex: 1;
}

.empty-state svg {
  opacity: 0.3;
  margin-bottom: 12px;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}

.add-todo {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  padding-top: 12px;
  border-top: 1px solid var(--border-color);
}

.new-todo-input {
  flex: 1;
  font-size: 14px;
  padding: 10px 14px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: var(--bg-primary);
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.2s;
  min-height: 42px;
}

.new-todo-input:focus {
  border-color: var(--text-primary);
}

.new-todo-input::placeholder {
  color: var(--text-secondary);
}

.add-btn {
  padding: 10px 16px;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: opacity 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

.add-btn:hover {
  opacity: 0.85;
}

.add-btn:active {
  transform: scale(0.98);
}
</style>
